<template>
  <div id="wrapper" ref="wrapper">
    <div class="content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
  import BScroll from 'better-scroll'

  export default {
    name: "Scroll",
    props: {
      probeType:{
        type:Number,
        default:0
      },
      pullUpLoad:{
        type:Boolean,
        default: false,
      },
    },
    data(){
      return {
        scroll: null
      }
    },
    mounted() {
      // 1.创建BScroll对象
     this.scroll = new BScroll(this.$refs.wrapper,{
       click:true,
       probeType: this.probeType,
       pullUpLoad: this.pullUpLoad,
       observeImage: true
     })

      // 2.监听滚动的位置
      if(this.probeType === 2 || this.probeType === 3){
        //这里的scroll是better-scroll自带的事件
        this.scroll.on('scroll', (position) => {
          //而这里是发出去一个名为'scroll'的自定义事件
          this.$emit('scroll', position)
        })
      }

      // 3.监听scroll滚动到底部
      if(this.pullUpLoad){
        this.scroll.on('pullingUp', () => {
          // console.log('加载到底部');
          this.$emit('pullingUp')
        })
      }

    },
    methods:{
      scrollTo(x, y ,time = 300){
        //先判断scroll有没有出来再决定调不调用scrollTo
        //有时候scroll组件还没拿到图片加载完就已经发送事件了
        //导致scroll.refresh()的scroll还是null或者underfined
        this.scroll && this.scroll.scrollTo(x, y, time)
      },
      finishPullUp(){
        this.scroll && this.scroll.finishPullUp()
      },
      refresh(){
        this.scroll && this.scroll.refresh()
      }
    }

  }
</script>

<style scoped>

</style>